#ifndef __THREAD
#define __THREAD

#include <iostream>
#include <pthread.h>
#include <string>

class ThreadData;
typedef void (*func_t)(ThreadData*);

class ThreadData
{
public:
    ThreadData(const std::string &name, pthread_mutex_t *mutex)
        : _name(name), _mutex(mutex)
    {}

    std::string Name()
    {
        return _name;
    }

    pthread_mutex_t* GetLock()
    {
        return _mutex;
    }

    ~ThreadData()
    {}

private:
    pthread_mutex_t *_mutex;
    std::string _name;
};

class Thread
{
    // 执行函数
    static void *ThreadRoutine(void *args)
    {
        Thread *t = static_cast<Thread *>(args);
        t->Excute();
        return nullptr;
    }

    void Excute()
    {
        _isrunning = true;
        _func(_td);
        _isrunning = false;
    }

public:
    Thread(func_t func, ThreadData *td)
        : _func(func), _td(td)
    {}

    ~Thread()
    {}

    // 启动线程
    void Start()
    {
        pthread_create(&_tid, nullptr, ThreadRoutine, this);
        std::cout << _td->Name() << ", is start..." << std::endl;
    }

    // 终止线程
    void Stop()
    {
        if (_isrunning)
        {
            pthread_cancel(_tid);
            std::cout << _td->Name() << ", is stop..." << std::endl;
        }
    }

    // 等待线程
    void Join()
    {
        pthread_join(_tid, nullptr);
        std::cout << _td->Name() << ", is join..." << std::endl;
    }

private:
    func_t _func;
    pthread_t _tid;
    bool _isrunning;
    ThreadData *_td;
};

#endif